package wonder.console;

import java.io.Console;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import wonder.settings.SettingsManager;

public class Shell {
	private static final String NO_CONSOLE = "Error: Console unavailable";
	private static final String GREETINGS = "Welcome to 7w-wonders-api console.%n";
	private static final String UNKNOWN_COMMAND = "Unknown command [%1$s]%n";
	private static final String COMMAND_ERROR = "Command error [%1$s]: [%2$s]%n";

	private static final String TIME_FORMAT = "%1$tH:%1$tM:%1$tS";
	private static final String PROMPT = TIME_FORMAT + " $ ";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Console console = System.console();
		if (console != null) {
			setup();

			console.printf(GREETINGS);
			execCommandLoop(console);
		} else {
			throw new RuntimeException(NO_CONSOLE);
		}
	}

	private static void execCommandLoop(final Console console) {
		while (true) {
			String commandLine = console.readLine(PROMPT, new Date());
			Scanner scanner = new Scanner(commandLine);

			if (scanner.hasNext()) {
				final String commandName = scanner.next().toUpperCase();

				try {
					final Command cmd = Enum
							.valueOf(Command.class, commandName);

					List<String> params = new ArrayList<String>();
					while (scanner.hasNext()) {
						params.add(scanner.next());
					}

					cmd.exec(console, params, new Command.Listener() {
						@Override
						public void exception(Exception e) {
							console.printf(COMMAND_ERROR, cmd, e.getMessage());
						}
					});
				} catch (IllegalArgumentException e) {
					console.printf(UNKNOWN_COMMAND, commandName);
				}
			}

			scanner.close();
		}
	}

	private static void setup() {
		try {
			SettingsManager.standalone();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
